package com.xc.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ag.exception.SysTipsException;
import com.ag.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.xc.common.ServerResponse;
import com.xc.dao.SiteInfoMapper;
import com.xc.dao.UserMapper;
import com.xc.pojo.SiteInfo;
import com.xc.pojo.User;
import com.xc.service.ISiteInfoService;
import com.xc.service.ISiteSettingService;
import com.xc.stock.constant.AppVersionType;
import com.xc.stock.constant.AppVersionUpdateTag;
import com.xc.stock.domain.basic.entity.AppVersion;
import com.xc.stock.domain.basic.service.AppVersionService;
import com.xc.stock.domain.basic.service.UserStaffService;
import com.xc.stock.utils.Cons;
import com.xc.stock.utils.Utils;
import com.xc.utils.PropertiesUtil;
import com.xc.utils.redis.RedisShardedPool;

/**
 * 
 * title: InfoController.java 
 * description
 *
 * @author rplees
 * @email rplees.i.ly@gmail.com
 * @version 1.0  
 * @created Dec 4, 2018 10:22:44 PM
 */
@RestController
@RequestMapping("/api/")
public class InfoController {
	@Autowired ISiteSettingService iSiteSettingService;
	@Autowired SiteInfoMapper siteInfoMapper;
	@Autowired ISiteInfoService iSiteInfoService;
	@Autowired UserMapper userMapper;
	
	@Value("${db.url}")
	String dbUrl;
	
	@RequestMapping(value="/app/site/getInfo.do")
	public ServerResponse site_getInfo() {
		return iSiteInfoService.get();
	}
	
	@RequestMapping(value="resource/getSiteLogo.do")
	public void getSiteLogo(HttpServletResponse response) throws IOException {
		List<SiteInfo> list = siteInfoMapper.findAll();
		if(CollectionUtils.isEmpty(list)) {
			// 设置信息不存在
			throw new SysTipsException("tips.msg.183");
		}
		
		SiteInfo siteInfo = list.get(0);
		img(siteInfo.getSiteLogoPath(), response);
	}
	
	@RequestMapping(value="resource/getSiteLogoSm.do")
	public void getSiteLogoSm(HttpServletResponse response) throws IOException {
		List<SiteInfo> list = siteInfoMapper.findAll();
		if(CollectionUtils.isEmpty(list)) {
			// 设置信息不存在
			throw new SysTipsException("tips.msg.183");
		}
		
		SiteInfo siteInfo = list.get(0);
		img(siteInfo.getSiteLogoSmPath(), response);
	}
	
	void img(String value, HttpServletResponse response) throws IOException {
		response.setContentType("image/png");
		OutputStream os = response.getOutputStream();
		os.write(Base64.getDecoder().decode(value.getBytes()));
		os.flush();
		os.close();
	}
	
	@RequestMapping(value="resource/getUserImg1.do")
	public void getUserImg1(@RequestParam(required = false) Integer userId, HttpServletResponse response) throws IOException {
		User user = userMapper.selectByPrimaryKey(userId);
		if(user == null) {
			// 找不到用户信息
			throw new SysTipsException("tips.msg.186");
		}
		
		img(user.getImg1Path(), response);
	}
	
	@RequestMapping(value="resource/getUserImg2.do")
	public void getUserImg2(@RequestParam(required = false) Integer userId, HttpServletResponse response) throws IOException {
		User user = userMapper.selectByPrimaryKey(userId);
		if(user == null) {
			// 找不到用户信息
			throw new SysTipsException("tips.msg.186");
		}
		
		img(user.getImg2Path(), response);
	}
	
	@RequestMapping(value="service.do")
	public ServerResponse service(HttpServletRequest request) {
		User user = Utils.getCurrentUser(request);
		Integer agentId = user == null ? 0 : user.getAgentId();
		String serviceAddr = UserStaffService.of().findUserStaffServiceAddr(agentId);
		
		if(StringUtils.isBlank(serviceAddr)) {
			ServerResponse response = iSiteInfoService.get();
			if(! response.isSuccess()) {
				return response;
			}
			
			SiteInfo siteInfo = (SiteInfo) response.getData();
			serviceAddr = siteInfo.getOnlineService();
		}
		Map<String, Object> map = Maps.newHashMap();
		map.put("serviceUrl", serviceAddr);
		return ServerResponse.createBySuccess(map);
	}
	
	@RequestMapping({"/app/verison.do", "/app/version.do"})
	public ServerResponse<Map<String, Object>> version(HttpServletRequest request) {
		String deviceType = request.getHeader("DeviceType");
		String version = request.getHeader("version");
		AppVersionType appVersionType = AppVersionService.of().dy(deviceType);
		AppVersionUpdateTag tag = AppVersionUpdateTag.LATEST;
		AppVersion appVersion = null;
//		if(appVersionType == AppVersionType.USER_APP_ANDROID) {
			tag = AppVersionService.of().getUpdateTag(deviceType, version, Cons.QPlantForm.USER_APP);
			appVersion = AppVersionService.of().getLaseter(appVersionType);
//		}
		
		Map<String, Object> map = Maps.newHashMap();
		map.put("appVersion", appVersion);
		map.put("newUpdateTag", tag.code());
		return ServerResponse.createBySuccess(map);
	}
	
	@RequestMapping(value="info")
	public Map<String, Object> info(@RequestParam(required = false) String key) {
		RedisShardedPool.getJedis();
		Map<String, Object> map = Maps.newHashMap();
		map.put("dbUrl", dbUrl);
		map.put("redisIp", PropertiesUtil.getProperty("redis1.ip"));
		if(StringUtils.isNotBlank(key)) {
			map.put("key", PropertiesUtil.getProperty(key));
		}
		return map;
	}

	@RequestMapping(value="test.do")
	public Map<String, Object> test(@RequestParam(required = false) String key) {
		RedisShardedPool.getJedis();
		Map<String, Object> map = Maps.newHashMap();
		map.put("dbUrl", dbUrl);
		map.put("redisIp", PropertiesUtil.getProperty("redis1.ip"));
		map.put("marketServerList", JSON.toJSONString(Utils.marketServerList()));
		
		if(StringUtils.isNotBlank(key)) {
			map.put("key", PropertiesUtil.getProperty(key));
		}
		return map;
	}
}
